<?php

namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $table = 'dd_product';
    protected $primaryKey = 'id';
    public $timestamps = false;
    protected $guarded = array();
    /**
     * 获取二维码
     */
    public function getQRCode() {
        $url = urlencode(url("home/index/productshow/{$this->id}"));
        return url("home/index/qrcode?url={$url}");
    }
    
    /**
     * 判断产品是否存在
     */
    public static function hasProduct($id) {
        $product = static::find($id);
        return $product ? true : false;
    }
    /**
     * 添加新产品
     * @param \Illuminate\Http\Request $request
     * @return type
     */
    public static function addProduct(\Illuminate\Http\Request $request) {
        $pro = $request->all();
        $res = static::firstOrCreate($pro);
        if ($res) {
            return \Illuminate\Support\Facades\Response::json([
                'status'    => 1,
                'info'      => '添加成功'
            ]);
        } else {
            return \Illuminate\Support\Facades\Response::json([
                'status'    => 0,
                'info'      => '添加失败'
            ]);
        }
    }
    
    /**
     * 产品类型
     */
    public function strPtype() {
        $ptype = \Illuminate\Support\Facades\Config::get('global.site.ptype');
        return $ptype[$this->ptype] ? $ptype[$this->ptype] : "";
    }
    /**
     * 产品月均价格
     */
    public function strMonthPrice() {
        $month = intval($this->lot) * 12 == 0 ? 12 : intval($this->lot) * 12;
        return number_format($this->price/$month, 2);
    }
    
    /**
     * 产品速率
     */
    public function strPcate() {
        $pcate = Pcate::find($this->pcateid);
        return $pcate ? $pcate->name : "未知";
    }
    
    /**
     * 产品小区优惠
     */
    public function strPlotFav($plotid, $type=1) {
        $plotfav = Plotfav::where("plotid", $plotid)->where("productid", $this->id)->first();
        if ($plotfav) {
            if ($type==1) {
                return $plotfav->plotfav;
            } elseif ($type == 2) {
                return $plotfav->plotinit;
            }
        } else {
            return 0;
        }
    }
    
    /**
     * 产品小区初装费
     */
    
}
